﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;

using CE.Configuration;
using CE.Global;
using CE.User;
using CE.Image;
using CE.CarInsurance;
using CE.Company;
using CE.Database;
using CE.Security;

public partial class car_insurance_car_quote : MyLanguageBasePage
{
    string _redirectUrl = "";
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.CITitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.CIKeyword;
        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.CIDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        if (!IsPostBack)
        {
            lblInteractMessageHeader.Text = Resources.General.CQSelectCarYear;
            lblInteractMatches.Text = Resources.General.CQFound + " <b>0</b> " + Resources.General.CQMatches;
            //CE.Email.Welcome.SendMail("kandasamy.sakthivel@comparexpress.com", "GG Tester", "testing");
            //CE.Email.Welcome.SendMail("sakthivel.kandasamy@teledirect.com.my", "GG Tester", "testing");
            //SendAsyncEmail(sender,e);            
            LoadManufactYearList();
            ClearAllList();
            GetCarQuoteCountLast30Days(ddlCarMake.Text, ddlModelBodyCCDoor.Text, ddlCarMake.SelectedItem.Text, ddlModelBodyCCDoor.SelectedItem.Text);
            lblSteps.Text = Resources.CarInsurance.Step1; // "<u>Step 1:</u><br />Please select your Car Manufacture Year in the list";
            hplCallforDiscount.NavigateUrl = CE.Global.General.GetUrl("/car-insurance/call-me", Page);
            if (Session["Language"] != null & Session["Language"].ToString() == "en-US")
            {
                //imgStp1.Width = 140;
                //imgStp1.Height = 35;
                //imgStp2.Width = 171;
                //imgStp2.Height = 35;
                //imgStp3.Width = 140;
                //imgStp3.Height = 35;
            }
            else if (Session["Language"] != null & Session["Language"].ToString() == "th-TH")
            {
                //imgStp1.Width = 140;
                //imgStp1.Height = 35;
                //imgStp2.Width = 84;
                //imgStp2.Height = 35;
                //imgStp3.Width = 140;
                //imgStp3.Height = 35;
            }

            HttpCookie _cookie = Request.Cookies.Get("GGQuote");
            if (_cookie != null)
            {
                //divTopNavigation.Visible = true;
                GetCookies();
                txtUserEmail.ControlStyle.CssClass = "cb-fields-disable";
                txtUserName.ControlStyle.CssClass = "cb-fields-disable";
                txtUserMobile.ControlStyle.CssClass = "cb-fields-disable";
            }
            else
            {
                //divTopNavigation.Visible = false;
                txtUserEmail.ControlStyle.CssClass = "cb-fields";
                txtUserName.ControlStyle.CssClass = "cb-fields";
                txtUserMobile.ControlStyle.CssClass = "cb-fields";
            }
            ddlManufactYear.Attributes.Add("onblur", "ShowValidationEffect('" + ddlManufactYear.ClientID + "','" + rfvManufactYear.ClientID + "');");
            ddlCarMake.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCarMake.ClientID + "','" + rfvCarMake.ClientID + "');");
            ddlModelBodyCCDoor.Attributes.Add("onblur", "ShowValidationEffect('" + ddlModelBodyCCDoor.ClientID + "','" + rfvModelBodyCCDoor.ClientID + "');");

            txtUserEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtUserEmail.ClientID + "','" + rfvUserEmail.ClientID + "','" + revUserEmail.ClientID + "');");
            txtUserName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtUserName.ClientID + "','" + rfvUserName.ClientID + "','" + revUserName.ClientID + "');");
            txtUserMobile.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtUserMobile.ClientID + "','" + rfvUserMobile.ClientID + "','" + revUserMobile.ClientID + "');");

            Page.Form.DefaultButton = btnGetaQuote.UniqueID;
            General.ClearAllSession(this.Page, "NEWCI");

            if (Session[General.UserId] != null)
            {
                ShowCustomerDetail(Convert.ToInt64(Session[General.UserId]));
            }
            if (Session[CE.Global.General.IsAcceptTC] != null)
            {
                checkIsAgreement.Checked = true;
                if (Session[CE.Global.General.IsAcceptTC].ToString() != "1")
                {
                    checkIsAgreement.Checked = false;
                }
            }
            //Sakthi Added on 12 Jun 2014 - Start
            Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);
            string rq_type = HttpUtility.ParseQueryString(theRealURL.Query).Get("type");
            if (rq_type != null && rq_type != string.Empty)
            {
                hdnURLFrom.Value = Server.HtmlEncode(rq_type.ToString()).Trim().ToLower();
                if (rq_type.ToLower() == "hmp")
                {
                    LogUserViewedHistory("CQHP", "Car Quote from Home Page");
                }
                else if (rq_type.ToLower() == "bci")
                {
                    LogUserViewedHistory("CQB", "Car Quote from Best Car Insurance Page");
                }
            }
            //Sakthi Added on 12 Jun 2014 - End

            #region Promotion Display
            string _CNYPromo = CE.Global.General.GetUTCDateTime().ToString("yyyyMMdd");
            Int64 _intCNYPromo = 0;
            if (!Int64.TryParse(_CNYPromo, out _intCNYPromo))
            {
                _intCNYPromo = 0;
            }
            if (Session["Language"] != null & Session["Language"].ToString() == "en-US")
            {
                if (_intCNYPromo >= 20150202 && _intCNYPromo <= 20150227)
                {
                    divCNYPromotion.Visible = true;
                    divCarQuoteNormal.Visible = false;
                    upPopupResult.Visible = false;
                    hdnIsPromo.Value = "1";
                }
            }
            else if (Session["Language"] != null & Session["Language"].ToString() == "th-TH")
            {
                if (_intCNYPromo >= 25580202 && _intCNYPromo <= 25580227)
                {
                    divCNYPromotion.Visible = true;
                    divCarQuoteNormal.Visible = false;
                    upPopupResult.Visible = false;
                    hdnIsPromo.Value = "1";
                }
            }
            #endregion

            Session["fromProvider"] = null;
        }
    }

    protected void btnGetaQuote_Click(object sender, EventArgs e)
    {
        try
        {
            ChangeValidationEffectServerSide("carquote");
            Page.Validate("carquote");
            if (Page.IsValid)
            {
                string CarModel = Resources.CarInsurance.YourCarModel + ": " + hidCarMakeName.Value + " " + GetCarModelName();
                lblCarModelName.Text = CarModel;

                #region Added on 27 Oct 2014 for Get Car Quote Result Count
                Save();
                int _intPremiumCount = CalculatePremium();
                if (_intPremiumCount >= 5)
                {
                    lblResultCount.Text = _intPremiumCount.ToString();
                }
                int _intInsurerCount = GetTempResultTableTwo();
                if (_intInsurerCount >= 5)
                {
                    lblInsurerCount.Text = _intInsurerCount.ToString();
                }
                #endregion

                HttpCookie cookies = Request.Cookies["GGQuote"];
                if (cookies != null)
                {
                    checkIsAgreement.Checked = true;
                    txtIsAccept.Text = "1";
                    ViewResult();
                }
                else
                {

                    ///to do lee
                    ViewResult();
                   //mpeUserLogin.Show();
                }

                #region Hide on 23 Oct 2014 for Check Email and Mobile number
                //HttpCookie _cookie = Request.Cookies.Get("GGQuote");
                //if (_cookie == null)
                //{
                //    mpeUserLogin.Show();
                //}
                //else
                //{
                //    if (Save())
                //    {
                //        Int64 _userId = 0;
                //        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
                //        bool _newuser = false;
                //        if (Session[General.UserId] != null)
                //        {
                //            _userId = Convert.ToInt64(Session[General.UserId].ToString());
                //        }
                //        else
                //        {
                //            _newuser = true;
                //        }

                //        #region Page Source
                //        ////Sakthi Added on 12 Jun 2014 - Start
                //        //int _intSourceId = 0;
                //        //if (hdnURLFrom.Value != null && hdnURLFrom.Value != string.Empty && hdnURLFrom.Value == "hm")
                //        //{
                //        //    _intSourceId = 1;
                //        //}
                //        //else if (hdnURLFrom.Value != null && hdnURLFrom.Value != string.Empty && hdnURLFrom.Value == "bci")
                //        //{
                //        //    _intSourceId = 2;
                //        //}
                //        //if (_intSourceId > 0 && _carId > 0)
                //        //{
                //        //    UpdateCarQuotePageSourceId(_intSourceId, _carId);
                //        //}
                //        ////Sakthi Added on 12 Jun 2014 - End
                //        #endregion

                //        if (UpdateProfile(_userId, _carId) > 0)
                //        {
                //            if (_newuser)
                //            {
                //                SendMailToUser(txtUserEmail.Text.Trim().ToLower(), Session[CE.Global.General.UserName].ToString(), txtUserMobile.Text.Trim()); //txtEmailAddress.Text.Trim()
                //            }
                //            Session["CLASSTYPE"] = "1";
                //            Session["FROMCARDETAIL"] = "1";
                //            string url = CE.Global.General.GetUrl("/car-insurance/car-quote-results", Page);
                //            Response.Redirect(url, false);

                //        }
                //        else
                //        {
                //            mpeUserLogin.Show();
                //        }
                //    }
                //}
                #endregion
            }
        }
        catch (Exception ex)
        {
        }
    }

    private Int32 CalculatePremium()
    {
        int _result = 0;
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();

        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefUserId", _userId);

        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);

        //select car detail
        _db = new MyDatabase();
        _sPara = new SortedList();
        DataTable _dt = new DataTable("tblModelBody");
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", _userId);
        _dt = _db.GetDataTableBySP("[sprocCarDetailTHSelectSingleItem]", _sPara);
        string[] makeName;
        makeName = _dt.Rows[0]["MakeModelDesc"].ToString().Split(' ');

        if (_dt.Rows.Count > 0)
        {

            _db = new MyDatabase();
            _sPara = new SortedList();
            _sPara.Add("@CarId", Session[General.CarId].ToString());
            _sPara.Add("@RefUserId", _userId);

            BKIDetailDB bki = new BKIDetailDB();

            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
            {
                if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AZCPProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocAZCPCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocAXACarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocMSIGCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocLMGCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocChartisCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatProviderCompanyID"))
                    _result = _db.ExecuteNonSqlSP("[sprocTVVCarInsuranceCalculation]", _sPara);
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIProviderCompanyID"))
                {
                    try
                    {
                        //BKICalculationWithTimeout(_carId, _userId);
                    }
                    catch
                    {
                    }

                    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationBKI]", _sPara);
                }
            }
            else
            {
                //====Test Web Service
                try
                {
                    //BKICalculationWithTimeout(_carId, _userId);
                }
                catch
                {
                }

                //_result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationWithResultCounting]", _sPara);
                _result = (int)_db.ExecuteSP("[sprocProviderCarInsuranceCalculationWithAllInsuranceType]", _sPara);
            }
            return _result;
            //}
        }
        return 0;
    }

    private Int32 GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemList]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());

        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        if (_dtResult.Rows.Count > 0)
        {
        }
        else
        {
            Session["UMMSG"] = "CI,5000";
        }

        DataView view = new DataView(_dtResult);
        DataTable distinctValues = view.ToTable(true, "ProviderCompanyId");

        return distinctValues.Rows.Count;
    }

    protected void btnViewResultsNow_Click(object sender, EventArgs e)
    {
        //ViewResult();
        if (hiddenFacebookID.Value == "")
        {
            ViewResult();
        }
        else
        {
            ViewResultWithFBLogin();
        }
    }

    protected void ViewResult()
    {
        try
        {
            Int64 _userId = 0;
            Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }
            #region Page Source
            //Sakthi Added on 12 Jun 2014 - Start
            int _intSourceId = 0;
            if (hdnURLFrom.Value != null && hdnURLFrom.Value != string.Empty && hdnURLFrom.Value == "hmp")
            {
                _intSourceId = 1;
            }
            else if (hdnURLFrom.Value != null && hdnURLFrom.Value != string.Empty && hdnURLFrom.Value == "bci")
            {
                _intSourceId = 2;
            }
            if (_intSourceId > 0 && _carId > 0)
            {
                UpdateCarQuotePageSourceId(_intSourceId, _carId);
            }
            //Sakthi Added on 12 Jun 2014 - End
            #endregion


            Session["CLASSTYPE"] = "1";
            Session["FROMCARDETAIL"] = "1";
            Response.Redirect(CE.Global.General.GetUrl("/car-insurance/car-quote-results", Page));

        }
        catch (Exception ex)
        {
        }
    }

    private void LogUserViewedHistory(string PageType, string Description)
    {
        //UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        //_userviewdb.LogViewedHistory(PageType, Request, Description);  
        LogViewedHistory(PageType, Request, Description);
    }

    public Int64 LogViewedHistory(string PageType, HttpRequest ClientRequest, string Description)
    {
        try
        {
            UserViewHistory _userview = new UserViewHistory();
            UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
            string _ipNumber = ClientRequest.UserHostAddress;
            string _browsertype = ClientRequest.Browser.Type;
            string _pageType = PageType;
            string _viewDate = General.GetUTCDateTime().ToString("yyyyMMdd");
            string _browserInfo = "";
            Int64 _retViewedDetailId = 0;

            _browserInfo += "<UserBrowser>";
            _browserInfo += "<Browser>" + ClientRequest.Browser.Browser + "</Browser>";
            _browserInfo += "<Type>" + ClientRequest.Browser.Type + "</Type>";
            _browserInfo += "<Version>" + ClientRequest.Browser.Version + "</Version>";
            _browserInfo += "<MajorVersion>" + ClientRequest.Browser.MajorVersion.ToString() + "</MajorVersion>";
            _browserInfo += "<MinorVersionString>" + ClientRequest.Browser.MinorVersionString + "</MinorVersionString>";

            _browserInfo += "<JavaScript>" + ClientRequest.Browser.JavaScript.ToString() + "</JavaScript>";
            _browserInfo += "<VBScript>" + ClientRequest.Browser.VBScript.ToString() + "</VBScript>";
            _browserInfo += "<ActiveXControls>" + ClientRequest.Browser.ActiveXControls.ToString() + "</ActiveXControls>";
            _browserInfo += "<Frames>" + ClientRequest.Browser.Frames.ToString() + "</Frames>";
            _browserInfo += "<Tables>" + ClientRequest.Browser.Tables.ToString() + "</Tables>";
            _browserInfo += "<Cookies>" + ClientRequest.Browser.Cookies.ToString() + "</Cookies>";
            //_browserInfo += "<ClrVersion>" + ClientRequest.Browser.ClrVersion.ToString() + "</ClrVersion>";
            _browserInfo += "<JavaApplets>" + ClientRequest.Browser.JavaApplets.ToString() + "</JavaApplets>";

            _browserInfo += "<Win16>" + ClientRequest.Browser.Win16.ToString() + "</Win16>";
            _browserInfo += "<Win32>" + ClientRequest.Browser.Win32.ToString() + "</Win32>";
            _browserInfo += "<Platform>" + ClientRequest.Browser.Platform + "</Platform>";
            _browserInfo += "<UserAgent>" + ClientRequest.UserAgent + "</UserAgent>";
            _browserInfo += "<UserHostAddress>" + ClientRequest.UserHostAddress + "</UserHostAddress>";
            _browserInfo += "<UserHostName>" + ClientRequest.UserHostName + "</UserHostName>";

            _browserInfo += "<IsSecureConnection>" + ClientRequest.IsSecureConnection.ToString() + "</IsSecureConnection>";
            _browserInfo += "<AnonymousID>" + ClientRequest.AnonymousID + "</AnonymousID>";
            _browserInfo += "<ContentLength>" + ClientRequest.ContentLength.ToString() + "</ContentLength>";
            _browserInfo += "<ContentType>" + ClientRequest.ContentType.ToString() + "</ContentType>";
            _browserInfo += "<HttpMethod>" + ClientRequest.HttpMethod + "</HttpMethod>";
            _browserInfo += "</UserBrowser>";

            _userview = _userviewdb.GetUserViewHistory(_ipNumber, _pageType, _browsertype, _viewDate);
            if (_userview == null)
            {
                _userview = new UserViewHistory();
                _userview.IPNumber = _ipNumber;
                _userview.PageType = _pageType;
                _userview.BrowserType = _browsertype;
                _userview.BrowserInfo = _browserInfo;
                _userview.ViewedCount = 1;
                _userview.ViewedDescription = Description;
                _retViewedDetailId = _userviewdb.Insert(_userview);
            }
            else
            {
                _userview.ViewedCount += 1;
                _userview.ViewedDescription = Description;
                _retViewedDetailId = _userviewdb.Insert(_userview);
            }
            _userview = null;
            return _retViewedDetailId;
        }
        catch (Exception ex)
        {
            return 1;
        }
    }

    public Int64 UpdateCarQuotePageSourceId(int SourceId, Int64 CarId)
    {
        try
        {
            MyDatabase _dbUpdate = new MyDatabase();
            SortedList _spList = new SortedList();
            string _spName = "sprocCarQuotePageSourceIdUpdateSingleItem";

            _spList.Add("@CarId", CarId);
            _spList.Add("@SourceId", SourceId);

            object _retObject = _dbUpdate.ExecuteSP(_spName, _spList);
            return Convert.ToInt64(_retObject);
        }
        catch (Exception ex)
        {
            return -1;
        }
    }

    private void ShowCustomerDetail(Int64 UserId)
    {
        Profile _profile = new Profile();
        ProfileDB _profiledb = new ProfileDB();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            txtUserName.Text = _profile.FirstName;

            if (_profile.SurName != string.Empty)
            {
                txtUserName.Text += " " + _profile.SurName;
            }
            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                SetEmailAddress(_contact.Email);

                txtUserMobile.Text = _contact.Mobile;
                hidUserMobile.Value = _contact.Mobile;

            }
            _profile = null;
            //checkIsAgreement.Visible = false;
            //lblAgreement.Visible = false;
        }
    }

    private void SetEmailAddress(string emailaddress)
    {
        txtUserEmail.Text = emailaddress;

    }

    private void SetCookies()
    {
        //move to @car-quote-results.aspx
        //try
        //{
        //    //HttpCookie _cookie = new HttpCookie("GGQuote");
        //    //_cookie.Values.Add("CustomerName", MySecurity.Encrypt(txtUserName.Text, true));
        //    string _strName = txtUserName.Text;
        //    if (Session[CE.Global.General.UserName] != null)
        //    {
        //        _strName = Session[CE.Global.General.UserName].ToString();
        //    }

        //    HttpCookie _cookie = new HttpCookie("GGQuote");
        //    _cookie.Values.Add("CustomerName", MySecurity.Encrypt(_strName, true));
        //    _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(txtUserEmail.Text, true));
        //    _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(txtUserMobile.Text, true));

        //    _cookie.Expires = DateTime.Now.AddDays(90);
        //    Response.Cookies.Add(_cookie);
        //}
        //catch (Exception Ex)
        //{
        //    Ex = null;
        //}
    }

    private void GetCookies()
    {
        try
        {
            HttpCookie _cookie = Request.Cookies.Get("GGQuote");
            if (_cookie != null)
            {
                txtUserName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtUserEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                string _mobile = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                txtUserMobile.Text = _mobile;
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private void LoadManufactYearList()
    {
        //int _yearCount = 14;
        int _yearCount = 13;
        ddlManufactYear.Items.Clear();

        int _startYear = General.GetUTCDateTime().Year - _yearCount;
        //int _endYear = General.GetUTCDateTime().Year;
        int _endYear = General.GetUTCDateTime().Year - 1;
        for (int i = _endYear; i >= _startYear; i--)
        {
            if (CultureInfo.CurrentCulture.Name != "th-TH")
            {
                ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            else
            {
                ddlManufactYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
            }
        }
        ddlManufactYear.Items.Insert(0, new ListItem(Resources.General.SelectCarYear, "-1"));
        //ddlManufactYear.Items.Insert(0, new ListItem("Select", "-1"));
    }

    protected void ddlManufactYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string carMakeValue = ddlCarMake.Text;
            string carModelValue = ddlModelBodyCCDoor.Text;

            if (ddlManufactYear.Text == "-1")
            {
                ClearAllList();

                lblInteractMessageHeader.Text = Resources.General.CQSelectCarYear;// "Select your car manufacture year";
                lblInteractCarYear.Text = Resources.General.Year;
                lblInteractCarBrand.Text = Resources.General.CQCarMake;
                lblInteractMatches.Text = Resources.General.CQFound + " <b>0</b> " + Resources.General.CQMatches;
                lblInteractMessage.Text = "";
                divInteractCarYear.Attributes.Add("class", "year-grey");
                //divInteractCarBrand.Style.Add("visibility", "hidden");
                divInteractCarBrandInner1.Attributes.Add("class", "car-brand-grey");
                divInteractCarBrandInner2.Attributes.Add("class", "amount-grey");
                divInteractMessage.Style.Add("visibility", "hidden");
                lblInteractMatches.Style.Add("margin-left", "0");
            }
            else
            {
                GetCarMakeList(ddlManufactYear.Text, ddlCarMake);
                GetCarQuoteCountLast30Days(ddlCarMake.Text, ddlModelBodyCCDoor.Text, ddlCarMake.SelectedItem.Text, ddlModelBodyCCDoor.SelectedItem.Text);
                if (ddlCarMake.Items.Count > 0)
                {
                    lblSteps.Text = Resources.CarInsurance.Step2; //"<u>Step 2:</u><br />Select your Car make in the list";
                    if (carMakeValue != "-1")
                    {
                        ddlCarMake.Text = carMakeValue;
                        ddlCarMake_SelectedIndexChanged(sender, e);

                        if (carModelValue != "-1" && ddlModelBodyCCDoor.Items.Count > 0)
                        {
                            ddlModelBodyCCDoor.Text = carModelValue;
                            ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
                        }
                    }
                    else
                    {
                    }
                }

                lblInteractMessageHeader.Text = "";
                lblInteractCarYear.Text = ddlManufactYear.SelectedItem.Text;
                if (ddlManufactYear.Text != "-1")
                {
                    lblInteractCarYear.Text = ddlManufactYear.Text;
                }
                lblInteractCarBrand.Text = Resources.General.CQCarMake;// "Select car make";
                lblInteractMatches.Text = Resources.General.CQFound + " <b>0</b> " + Resources.General.CQMatches;
                divInteractCarYear.Attributes.Add("class", "year");
                //divInteractCarBrand.Style.Add("visibility", "visible");
                divInteractCarBrandInner1.Attributes.Add("class", "car-brand-grey");
                divInteractCarBrandInner2.Attributes.Add("class", "amount-grey");
                lblInteractMatches.Style.Add("margin-left", "0");
            }
        }
        catch (Exception ex)
        {

        }
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.General.SelectCarModel, "-1"));
            //ddlModelBodyCCDoor.Items.Add(new ListItem("Select", "-1"));
            txtSumInsured.Text = "0";
            lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";

            lblInteractCarBrand.Text = Resources.General.CQCarMake;// "Select car make";
            lblInteractMatches.Text = Resources.General.CQFound + " <b>0</b> " + Resources.General.CQMatches;
            lblInteractMessage.Text = "";
            divInteractCarBrandInner1.Attributes.Add("class", "car-brand-grey");
            divInteractCarBrandInner2.Attributes.Add("class", "amount-grey");
            divInteractMessage.Style.Add("visibility", "hidden");
            lblInteractMatches.Style.Add("margin-left", "0");
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlManufactYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                lblSteps.Text = Resources.CarInsurance.Step3; //"<u>Step 3:</u><br />Select your Car model in the list";
                GetCarQuoteCountLast30Days(ddlCarMake.Text, ddlModelBodyCCDoor.Text, ddlCarMake.SelectedItem.Text, ddlModelBodyCCDoor.SelectedItem.Text);
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }

            lblInteractMessageHeader.Text = "";
            lblInteractCarYear.Text = ddlManufactYear.Text;
            if (ddlManufactYear.Text == "-1")
            {
                lblInteractCarYear.Text = ddlManufactYear.SelectedItem.Text;
            }
            lblInteractCarBrand.Text = ddlCarMake.SelectedItem.Text;
            lblInteractMatches.Text = Resources.General.CQFound + " <b>" + (ddlModelBodyCCDoor.Items.Count - 1) + "</b> " + Resources.General.CQMatches;
            lblInteractMessage.Text = "";
            divInteractCarBrandInner1.Attributes.Add("class", "car-brand");
            divInteractCarBrandInner2.Attributes.Add("class", "amount");
            lblInteractMatches.Style.Add("margin-left", "0");
        }
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.General.SelectCarMake, "-1"));
        //ddlCarMake.Items.Add(new ListItem("Select", "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.General.SelectCarModel, "-1"));
        //ddlModelBodyCCDoor.Items.Add(new ListItem("Select", "-1"));
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.General.SelectCarMake, "-1"));
        //ddlList.Items.Insert(0, new ListItem("Select", "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelDescTHListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.General.SelectCarModel, "-1"));
        //ddlModelBodyCCDoor.Items.Add(new ListItem("Select", "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            ddlModelBodyCCDoor.DataSource = _dt;
            ddlModelBodyCCDoor.DataValueField = "CarModelDesc";
            ddlModelBodyCCDoor.DataTextField = "CarModelDisplay";
            ddlModelBodyCCDoor.DataBind();
            ddlModelBodyCCDoor.Items.Insert(0, new ListItem(Resources.General.SelectCarModel, "-1"));
            //ddlModelBodyCCDoor.Items.Insert(0, new ListItem("Select", "-1"));
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.General.SelectCarModel, "-1"));
            //ddlList.Items.Insert(0, new ListItem("Select", "-1"));
        }
        _dt = null;
        _db = null;
    }

    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 4)
            {
                _model = _tempDesc[0];
                _body = "-";// _tempDesc[2] == "2" ? "PICKUP" : "";
                _cc = _tempDesc[1].Substring(0, _tempDesc[1].Length - 2);
                _door = _tempDesc[2];
            }
            else if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlManufactYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
            if (ddlModelBodyCCDoor.Text != "-1")
            {
                lblSteps.Text = Resources.CarInsurance.Step4; //"Please click the Get a Quote button and wait 5 seconds for your quote results.";
                GetCarQuoteCountLast30Days(ddlCarMake.Text, _model, ddlCarMake.SelectedItem.Text, _model.Trim().Replace('_', ' '));
                //GetCarQuoteCountLast30Days(ddlCarMake.Text, _model, ddlCarMake.SelectedItem.Text, ddlModelBodyCCDoor.SelectedItem.Text.Trim().Replace('_', ' '));
            }

            if (ddlModelBodyCCDoor.Text != "-1")
            {
                string _strSelectedCarModel = "", _strAutoMan = "";
                string[] _strSelectedCarModelSplite = ddlModelBodyCCDoor.SelectedItem.Text.Split(',');
                if (_strSelectedCarModelSplite.Length == 5)
                    _strSelectedCarModel = _strSelectedCarModelSplite[0] + "," + _strSelectedCarModelSplite[1];
                else
                    _strSelectedCarModel = _strSelectedCarModelSplite[0];

                if (_strSelectedCarModel.Contains(" Auto "))
                {
                    _strSelectedCarModel = _strSelectedCarModel.Replace(" Auto ", " ");
                    _strAutoMan = " <span style='font-size:80%;font-style: italic;'>(Auto)</span>";
                }
                else if (_strSelectedCarModel.Contains(" Man "))
                {
                    _strSelectedCarModel = _strSelectedCarModel.Replace(" Man ", " ");
                    _strAutoMan = " <span style='font-size:80%;font-style: italic;'>(Manual)</span>";
                }
                _strSelectedCarModel = _strSelectedCarModel.Replace("_", " ");

                lblInteractMessageHeader.Text = "";
                if (ddlManufactYear.Text == "-1")
                {
                    lblInteractCarYear.Text = ddlManufactYear.SelectedItem.Text;
                }
                lblInteractCarYear.Text = ddlManufactYear.Text;
                lblInteractCarBrand.Text = ddlCarMake.SelectedItem.Text;
                //lblInteractMessage.Text = "We have found <b>" + ddlModelBodyCCDoor.Items.Count + "</b> matches";
                //lblInteractMatches.Text = Resources.General.CQFound + " <b>" + (ddlModelBodyCCDoor.Items.Count - 1) + "</b> " + Resources.General.CQMatches;
                lblInteractMessage.Text = _strSelectedCarModel + _strAutoMan;
                divInteractMessage.Style.Add("visibility", "visible");
                lblInteractMatches.Text = Resources.General.CQClickGetQuote;
                lblInteractMatches.Style.Add("margin-left", "-54px");
            }
            else
            {
                lblInteractMessageHeader.Text = "";
                if (ddlManufactYear.Text == "-1")
                {
                    lblInteractCarYear.Text = ddlManufactYear.SelectedItem.Text;
                }
                lblInteractCarYear.Text = ddlManufactYear.Text;
                lblInteractCarBrand.Text = ddlCarMake.SelectedItem.Text;
                //lblInteractMessage.Text = "We have found <b>" + ddlModelBodyCCDoor.Items.Count + "</b> matches";
                lblInteractMatches.Text = Resources.General.CQFound + " <b>" + (ddlModelBodyCCDoor.Items.Count - 1) + "</b> " + Resources.General.CQMatches;
                lblInteractMessage.Text = "";
                divInteractMessage.Style.Add("visibility", "hidden");
                lblInteractMatches.Style.Add("margin-left", "0");
            }
        }
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private string[] GetCarModelSumInsuredAmountAndVehicleType_New(string CarMake, string CarModel, string Body, string CC, string Door, string Year)
    {
        string[] _strReturn = new string[2];
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            _strReturn[0] = _dt.Rows[0][0].ToString(); //SumInsured
            _strReturn[1] = _dt.Rows[0][1].ToString(); //CarVehicleType
        }
        else
        {
            _strReturn[0] = "0";
        }
        _dt = null;
        _db = null;

        return _strReturn;
    }

    private string GetCarModelGroupNo_New(string CarMake, string CarModel, string Body, string CC, string Door)
    {
        string _strReturn = "";
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            _strReturn = _dt.Rows[0][0].ToString();
        }
        else
        {
            _strReturn = "-1";
        }
        _dt = null;
        _db = null;

        return _strReturn;
    }

    private bool Save()
    {
        Int64 _carresult = 0;
        Int64 _policyresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        Int64 _refceuserid = 92278;
        string Commencemonth = General.GetUTCDateTime().AddDays(14).ToString("ddMMyyyy");

        if (Session[General.CarId] != null)
        {
            _car = _cardb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), 0);
            if (Session[General.AgentId] != null)
            {
                _car.Info5 = "UPDATE";
            }
        }
        else
        {
            if (Session[General.AgentId] != null)
            {
                _car.Info4 = "NEW";
            }
        }
        if (_car == null)
        {
            _car = new CarDetailTH();
        }


        _car.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);

        if (Session[General.AgentId] != null)
        {
            _car.Info2 = Session[General.AgentId].ToString();
            _car.Info3 = General.GetUTCDateTime().ToString();
        }

        _car.CarMakeName = hidCarMake.Value;
        string[] _tempDesc = hidModelBodyCCDoor.Value.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }

        string _model = "";
        string _body = "";
        string _cc = "";
        string _door = "";
        if (_tempDesc.Length == 4)
        {
            _model = _tempDesc[0];
            _body = "-";// _tempDesc[2] == "2" ? "PICKUP" : "";
            _cc = _tempDesc[1].Substring(0, _tempDesc[1].Length - 2);
            _door = _tempDesc[2];
        }
        else if (_tempDesc.Length == 5)
        {
            _model = _tempDesc[0];
            _body = _tempDesc[1];
            _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
            _door = _tempDesc[3];
        }
        else if (_tempDesc.Length == 6)
        {
            _model = _tempDesc[0] + " " + _tempDesc[1];
            _body = _tempDesc[2];
            _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
            _door = _tempDesc[4];
        }
        else if (_tempDesc.Length == 7)
        {
            _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _body = _tempDesc[3];
            _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
            _door = _tempDesc[5];
        }
        string[] _strResult = GetCarModelSumInsuredAmountAndVehicleType_New(hidCarMake.Value, _model, _body, _cc, _door, ddlManufactYear.Text);
        string _strSumInsured = _strResult[0];
        string _strCarVehicleType = _strResult[1];
        string _strGroupNo = GetCarModelGroupNo_New(hidCarMake.Value, _model, _body, _cc, _door);

        _car.GroupNo = Convert.ToInt32(_strGroupNo);
        _car.Info2 = _strCarVehicleType;

        //LC = 210 or 220
        //PS = 110 or 120
        //PU = 320
        //SV = 110 or 120
        if (_strCarVehicleType == "PS" || _strCarVehicleType == "SV" || _strCarVehicleType == "")
        {
            _car.Info3 = "110";
        }
        else if (_strCarVehicleType == "LC")
        {
            _car.Info3 = "210";
        }
        else if (_strCarVehicleType == "PU")
        {
            if (_car.Door == 4)
                _car.Info3 = "110";
            else
                _car.Info3 = "320";
        }

        //_car.Info3 = ddlVehicleType.Text;
        _car.MakeModelDesc = hidCarMakeName.Value + " " + hidModelBodyCCDoorName.Value;
        _car.Status = true;
        _car.RefCEUserId = _refceuserid;
        _car.CurrentStep = 1;
        _car.TotalStep = 4;

        _car.Info1 = "150";

        _carresult = _cardb.Insert(_car);

        _car = null;
        _cardb = null;

        if (_carresult > 0)
        {
            Session[CE.Global.General.CarId] = _carresult.ToString();

            if (hdnIsPromo.Value != null && hdnIsPromo.Value != string.Empty && hdnIsPromo.Value == "1")
            {
                //Update CarDetail Prmotion Value
                Int64 _result = -1;
                MyDatabase _db = new MyDatabase("TH.CX_DBConnectionString");
                string _spName = "sprocCarDetailTHInsertUpdateSingleItemPromotion";
                DataSet _dsAmount = new DataSet();
                SortedList _paraList = new SortedList();
                _paraList.Add("@CarId", _carresult);
                _paraList.Add("@PromoType", 2);
                _result = _db.ExecuteSP(_spName, _paraList);
                //End - Update CarDetail Prmotion Value
            }
        }
        else
        {
            //lblMessage.Text = "Insert error!";
        }
        if (_carresult > 0)
        {
            //CAR POLICY DETAILS
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());

            Int64 _carpolicyid = 0;

            if (Session[General.CarPolicyId] != null)
            {
                _carpolicyid = Convert.ToInt64(Session[General.CarPolicyId].ToString());
                _carpolicy.CECarPolicyId = _carpolicyid;
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info5 = "UPDATE";
                }
            }
            else
            {
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info4 = "NEW";
                }
            }

            //lblMessage.Text = "";
            if (Session[General.AgentId] != null)
            {
                _carpolicy.Info2 = Session[General.AgentId].ToString();
                _carpolicy.Info3 = General.GetUTCDateTime().ToString();
            }
            _carpolicy.CECarId = _carId;
            // 03/2013
            _carpolicy.InsuranceType = 10;
            _carpolicy.GarageType = Convert.ToInt32("1");
            _carpolicy.VehicleType = Convert.ToInt32("110");
            _carpolicy.SumInsured = Convert.ToInt32(_strSumInsured);
            _carpolicy.ProvinceRegistration = "BKK";
            _carpolicy.UseOfVehicle = "N/A";
            string strDate = Commencemonth;
            int _iDay = Convert.ToInt32(strDate.Substring(0, 2));
            int _iMonth = Convert.ToInt32(strDate.Substring(2, 2));
            int _iYear = Convert.ToInt32(strDate.Substring(4, 4)) > 2500 ? Convert.ToInt32(strDate.Substring(4, 4)) - 543 : Convert.ToInt32(strDate.Substring(4, 4));
            _carpolicy.CoverageCommenceDate = new DateTime(_iYear, _iMonth, _iDay);
            _carpolicy.IsRedPlate = false;

            _carpolicy.IsAddAccMod = false;
            _carpolicy.AddAccModAmount = 0;
            _carpolicy.NCDPercent = Convert.ToInt32("20");
            _carpolicy.IsClaimLastYear = false;
            _carpolicy.IsCTPL = false;

            _carpolicy.IsAddDriver = false;
            _carpolicy.NoOfDriver = 0;
            _carpolicy.Deductible = Convert.ToInt16("-1");
            _carpolicy.CurrentInsurer = "Others"; // Resources.CarInsurance.Others; 
            _carpolicy.RefCEUserId = _refceuserid;
            _carpolicy.Status = true;
            _carpolicy.CurrentStep = 2;
            _policyresult = _carpolicydb.Insert(_carpolicy);
            if (_policyresult > 0)
            {
                Session[General.CarPolicyId] = _policyresult.ToString();

                //lblMessage.Text += "<br />Car policy saved successfully!";
                //lblMessage.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                //lblMessage.Text = "Car policy did not save successfully!";
                //lblMessage.ForeColor = System.Drawing.Color.Red;
                return false;
            }
            CarDriver _cardriver = new CarDriver();
            CarDriverDB _cardriverdb = new CarDriverDB();
            
            _cardriverdb.UpdateAllStatus(_carId, _refceuserid);

            _carpolicy = null;
            _carpolicydb = null;
        }

        return _policyresult > 0;
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            AccountDB _useraccountdb = new AccountDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);
            _retValue = UserId;
            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = "";
                //txtUserName.Text = CE.Global.General.ClearScriptTag(txtUserName.Text.Trim());
                //_profile.FirstName = HttpUtility.HtmlEncode(txtUserName.Text);
                //_profile.SurName = "";
                if (hiddenFacebookID.Value == "")
                {
                    txtUserName.Text = CE.Global.General.ClearScriptTag(txtUserName.Text.Trim());
                    _profile.FirstName = HttpUtility.HtmlEncode(txtUserName.Text);
                    _profile.SurName = "";
                }
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M';
                }
                _profile.Status = "Complete";
                _profile.IsAcceptTC = checkIsAgreement.Checked;

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    //lee update rejected user
                    if (txtUserMobile.Text.Trim() != hidUserMobile.Value.Trim())
                    {
                        _useraccountdb.UnRejectUser(UserId);
                    }

                    _contact.Mobile = txtUserMobile.Text.Trim();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_profile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    if (_contact != null)
                    {
                        Session[General.UserPhoneNo] = _contact.Mobile;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) == Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        if (_retValue > 0 && CarId > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);


            Profile _profile = new CE.User.Profile();
            ProfileDB _profiledb = new ProfileDB();
            _profile = _profiledb.GetProfile(UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = txtUserEmail.Text.Trim().ToLower();
                _cardetail.Info6 = txtUserMobile.Text.Trim();
                _cardetail.Info7 = ""; //txtSurName.Text.Trim();
                txtUserName.Text = CE.Global.General.ClearScriptTag(txtUserName.Text.Trim());
                if (txtUserName.Text.Trim().Length > 0)
                {
                    _cardetail.Info8 = Server.HtmlEncode(txtUserName.Text.Trim());
                }
                if (_profile.Gender.ToString().Trim() != "")
                {
                    _cardetail.Info9 = _profile.Gender.ToString();
                }
                else
                {
                    _cardetail.Info9 = "M";
                }
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _cardetail.Info10 = dteDOB.ToString("dd-MMM-yyyy");
                }
                else
                {
                    _cardetail.Info10 = _profile.DOB.ToString("dd-MMM-yyyy");
                }
                _cardetail.Info11 = _profile.Occupation.ToString();
                _cardetail.Info12 = "";// ddlJobNature.GetJobNature();
                _cardetail.Info13 = "";// ddlMaritalStatus.GetMaritalStatus();
                _cardetail.Info14 = "";// ddlYearDriveSg.Text;
                _cardetail.Info15 = "";// ddlSalutation.GetSalutation();
                _cardetail.RefCEUserId = UserId;
            }
            _profile = null;

            //RefUserId only update
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            _carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            _retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            CarDetailTHDB cardb = new CarDetailTHDB();
            cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
            }
        }

        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;

        Account _useraccount = new Account();
        AccountDB _useraccountdb = new AccountDB();

        Profile _userprofile = new Profile();
        ProfileDB _userprofiledb = new ProfileDB();

        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));
        if (_useraccount != null)
        {
            if (_useraccount.CEID > 0)
            {
                _retVal = _useraccount.CEID;
                _contact = _contactdb.GetContact(_useraccount.CEID);
                Session[CE.Global.General.UserId] = _useraccount.CEID;
                Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                Session[CE.Global.General.UserEmail] = _useraccount.Email;
                Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                if (_userprofile != null && _userprofile.ProfileId > 0)
                {
                    if (_userprofile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _userprofile.SurName;
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_userprofile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                }
            }
        }
        else
        {
            //Meng Pan Added on 30 Jan 2015 - Start - Insert Facebook ID
            if (hiddenFacebookID.Value != "")
            {
                if (txtUserEmail.Text.Trim().ToLower() == hiddenFacebookEmail.Value.Trim().ToLower())
                {
                    txtUserName.Text = hiddenFacebookName.Value;
                    txtUserEmail.Text = hiddenFacebookEmail.Value;
                }
                else
                {
                    hiddenFacebookID.Value = "";
                }
            }
            //Meng Pan Added on 30 Jan 2015 - End - Insert Facebook ID

            long _result = -1;
            _useraccount = new Account();
            _useraccount.Email = txtUserEmail.Text.Trim().ToLower();
            string _authcode = txtUserMobile.Text.Trim();
            _useraccount.AuthCode = _authcode;
            _useraccount.UserId = "CEUSERAUTOIDCI";
            _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
            _useraccount.IsAcceptTC = false;
            _useraccount.Status = true;
            _useraccount.RefCEUserID = -1;
            _result = _useraccountdb.Insert(_useraccount);
            _useraccount.CEID = _result;
            _retVal = _useraccount.CEID;
            if (_result > 0)
            {
                _userprofile.Salutation = "";
                _userprofile.FirstName = Server.HtmlEncode(txtUserName.Text);
                _userprofile.SurName = "";
                DateTime dteDOB = new DateTime(1995, 1, 1);
                _userprofile.DOB = dteDOB;
                _userprofile.Gender = 'M';

                _userprofile.Occupation = Convert.ToInt32("54");
                _userprofile.Status = "Complete";
                _userprofile.RefCEUserId = _useraccount.CEID;
                _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                _result = _userprofiledb.Insert(_userprofile);

                _contact.Email = _useraccount.Email;
                _contact.Mobile = txtUserMobile.Text.Trim();

                _contact.Status = true;
                _contact.RefCEUserId = _useraccount.CEID;
                _result = _contactdb.Insert(_contact);

                if (_result > 0)
                {
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    if (_userprofile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _userprofile.SurName;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_userprofile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                }

            }

        }

        return _retVal;
        #endregion
    }

    private Int64 SaveNewCustomer_Old()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            //Hide on 13 Nov 2014 //_useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), txtUserMobile.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            //Hide on 23 Oct 2014 //if (_useraccountdb.IsAlreadyExist(txtUserEmail.Text.Trim().ToLower(), txtUserMobile.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
            if (_useraccount != null)
            {
                //Hide on 23 Oct 2014 //_useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), txtUserMobile.Text.Trim().ToLower(), 400);
                if (_useraccount.CEID > 0)
                {
                    _retVal = _useraccount.CEID;
                    _contact = _contactdb.GetContact(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }
                }
            }
            else
            {

                long _result = -1;
                _useraccount = new Account();
                _useraccount.Email = txtUserEmail.Text.Trim().ToLower();
                string _authcode = txtUserMobile.Text.Trim();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    _userprofile.Salutation = "";
                    _userprofile.FirstName = Server.HtmlEncode(txtUserName.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M';

                    _userprofile.Occupation = Convert.ToInt32("54");
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtUserMobile.Text.Trim();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtUserName.Text = HttpUtility.HtmlEncode(txtUserName.Text);
        txtUserEmail.Text = HttpUtility.HtmlEncode(txtUserEmail.Text);
        txtUserMobile.Text = HttpUtility.HtmlEncode(txtUserMobile.Text);

        #region Car Quotes
        //ManufactYear
        if (rfvManufactYear.Enabled && rfvManufactYear.ValidationGroup == strValidationGroup)
        {
            rfvManufactYear.Validate();
            if (rfvManufactYear.IsValid == false)
            {
                ddlManufactYear.ControlStyle.CssClass = "input-fields-dropdown validationError";
            }
            else
            {
                ddlManufactYear.ControlStyle.CssClass = "input-fields-dropdown";
            }
        }
        else
        {
            ddlManufactYear.ControlStyle.CssClass = "input-fields-dropdown";
        }

        //Car Make
        if (rfvCarMake.Enabled && rfvCarMake.ValidationGroup == strValidationGroup)
        {
            rfvCarMake.Validate();
            if (rfvCarMake.IsValid == false)
            {
                ddlCarMake.ControlStyle.CssClass = "input-fields-dropdown validationError";
            }
            else
            {
                ddlCarMake.ControlStyle.CssClass = "input-fields-dropdown";
            }
        }
        else
        {
            ddlCarMake.ControlStyle.CssClass = "input-fields-dropdown";
        }

        //Model
        if (rfvModelBodyCCDoor.Enabled && rfvModelBodyCCDoor.ValidationGroup == strValidationGroup)
        {
            rfvModelBodyCCDoor.Validate();
            if (rfvModelBodyCCDoor.IsValid == false)
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "input-fields-dropdown validationError";
            }
            else
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "input-fields-dropdown";
            }
        }
        else
        {
            ddlModelBodyCCDoor.ControlStyle.CssClass = "input-fields-dropdown";
        }

        #endregion

        #region Customer
        //Name
        if (rfvUserName.Enabled && rfvUserName.ValidationGroup == strValidationGroup)
        {
            rfvUserName.Validate();
            if (rfvUserName.IsValid == false)
            {
                txtUserName.ControlStyle.CssClass = "cb-fields validationError";
            }
            else
            {
                txtUserName.ControlStyle.CssClass = "cb-fields";
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "cb-fields";
        }

        if (revUserName.Enabled && revUserName.ValidationGroup == strValidationGroup)
        {
            if (rfvUserName.IsValid)
            {
                revUserName.Validate();
                if (revUserName.IsValid == false)
                {
                    txtUserName.ControlStyle.CssClass = "cb-fields validationError";
                }
                else
                {
                    txtUserName.ControlStyle.CssClass = "cb-fields";
                }
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "cb-fields";
        }

        //Email
        if (rfvUserEmail.Enabled && rfvUserEmail.ValidationGroup == strValidationGroup)
        {
            rfvUserEmail.Validate();
            if (rfvUserEmail.IsValid == false)
            {
                txtUserEmail.ControlStyle.CssClass = "cb-fields validationError";
            }
            else
            {
                txtUserEmail.ControlStyle.CssClass = "cb-fields";
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "cb-fields";
        }

        if (revUserEmail.Enabled && revUserEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvUserEmail.IsValid)
            {
                revUserEmail.Validate();
                if (revUserEmail.IsValid == false)
                {
                    txtUserEmail.ControlStyle.CssClass = "cb-fields validationError";
                }
                else
                {
                    txtUserEmail.ControlStyle.CssClass = "cb-fields";
                }
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "cb-fields";
        }

        //MobileNo
        if (rfvUserMobile.Enabled && rfvUserMobile.ValidationGroup == strValidationGroup)
        {
            rfvUserMobile.Validate();
            if (rfvUserMobile.IsValid == false)
            {
                txtUserMobile.ControlStyle.CssClass = "cb-fields validationError";
            }
            else
            {
                txtUserMobile.ControlStyle.CssClass = "cb-fields";
            }
        }
        else
        {
            txtUserMobile.ControlStyle.CssClass = "cb-fields";
        }

        if (revUserMobile.Enabled && revUserMobile.ValidationGroup == strValidationGroup)
        {
            if (rfvUserMobile.IsValid)
            {
                revUserMobile.Validate();
                if (revUserMobile.IsValid == false)
                {
                    txtUserMobile.ControlStyle.CssClass = "cb-fields validationError";
                }
                else
                {
                    txtUserMobile.ControlStyle.CssClass = "cb-fields";
                }
            }
        }
        else
        {
            txtUserMobile.ControlStyle.CssClass = "cb-fields";
        }
        #endregion

    }

    private void GetCarQuoteCountLast30Days(string CarMake, string CarModel, string CarMakeName, string CarModelName)
    {
        try
        {
            lbl30Days.Text = Resources.CarInsurance.Last30Days; //"Last 30 days We Quoted ";
            lblQuoteCar.Text = Resources.CarInsurance.QuotesFor; // " quotes for ";
            Int32 _TotalCount = 0;
            Int32 _CarMakeCount = 0;
            Int32 _CarModelCount = 0;
            MyDatabase _db = new MyDatabase();
            DataTable _dtCarQuoteCount = new DataTable("tblCarQuoteCount");
            SortedList _spList = new SortedList();
            _spList.Add("@CarMake", CarMake);
            _spList.Add("@CarModel", CarModel);
            _dtCarQuoteCount = _db.GetDataTableBySP("sprocGGCarQuoteCountLast30DaysSelectedItem", _spList);
            if (_dtCarQuoteCount != null && _dtCarQuoteCount.Rows.Count > 0)
            {
                if (!Int32.TryParse(_dtCarQuoteCount.Rows[0]["TotalCount"].ToString(), out _TotalCount))
                {
                    _TotalCount = 0;
                }
                if (!Int32.TryParse(_dtCarQuoteCount.Rows[0]["CarMakeCount"].ToString(), out _CarMakeCount))
                {
                    _CarMakeCount = 0;
                }
                if (!Int32.TryParse(_dtCarQuoteCount.Rows[0]["CarModelCount"].ToString(), out _CarModelCount))
                {
                    _CarModelCount = 0;
                }
            }
            if (_CarModelCount > 0)
            {
                lblQuotes.Text = _CarModelCount.ToString();
                lblQuoteCar.Text += CarMakeName + " " + CarModelName;
                divMotorBrand.Attributes.Add("class", GetMotorBrand(CarMake));
            }
            else if (_CarMakeCount > 0)
            {
                lblQuotes.Text = _CarMakeCount.ToString();
                lblQuoteCar.Text += CarMakeName;
                divMotorBrand.Attributes.Add("class", GetMotorBrand(CarMake));
            }
            else if (_TotalCount > 0)
            {
                lblQuotes.Text = _TotalCount.ToString();
                lblQuoteCar.Text += Resources.CarInsurance.AllCars; //" all Cars!";
                divMotorBrand.Attributes.Add("class", GetMotorBrand("GG"));
            }
            _dtCarQuoteCount = null;
            _db = null;
        }
        catch (Exception ex)
        {
        }
    }

    public string GetMotorBrand(string Brand)
    {
        string _strBrandClass = "gluaygluay";
        if (Brand == "AUDI")
        {
            _strBrandClass = "audi";
        }
        else if (Brand == "BMW")
        {
            _strBrandClass = "bmw";
        }
        else if (Brand == "CHER")
        {
            _strBrandClass = "chery";
        }
        else if (Brand == "CHEV")
        {
            _strBrandClass = "chevrolet";
        }
        else if (Brand == "CITR")
        {
            _strBrandClass = "citroen";
        }
        else if (Brand == "DAIH")
        {
            _strBrandClass = "daihatsu";
        }
        else if (Brand == "DFM")
        {
            _strBrandClass = "dfm";
        }
        else if (Brand == "FORD")
        {
            _strBrandClass = "ford";
        }
        else if (Brand == "HOND")
        {
            _strBrandClass = "honda";
        }
        else if (Brand == "HYUN")
        {
            _strBrandClass = "hyundai";
        }
        else if (Brand == "ISUZ")
        {
            _strBrandClass = "isuzu";
        }
        else if (Brand == "JAGU")
        {
            _strBrandClass = "jaguar";
        }
        else if (Brand == "JEEP")
        {
            _strBrandClass = "jeep";
        }
        else if (Brand == "KIA")
        {
            _strBrandClass = "kia";
        }
        else if (Brand == "LAND")
        {
            _strBrandClass = "landrover";
        }
        else if (Brand == "LEXU")
        {
            _strBrandClass = "lexus";
        }
        else if (Brand == "MAZD")
        {
            _strBrandClass = "mazda";
        }
        else if (Brand == "MERC")
        {
            _strBrandClass = "mercedes";
        }
        else if (Brand == "MINI")
        {
            _strBrandClass = "mini";
        }
        else if (Brand == "MITS")
        {
            _strBrandClass = "mitsubishi";
        }
        else if (Brand == "NISS")
        {
            _strBrandClass = "nissan";
        }
        else if (Brand == "PEUG")
        {
            _strBrandClass = "peugeot";
        }
        else if (Brand == "PORS")
        {
            _strBrandClass = "porsche";
        }
        else if (Brand == "PROT")
        {
            _strBrandClass = "proton";
        }
        else if (Brand == "SSAN")
        {
            _strBrandClass = "ssangyong";
        }
        else if (Brand == "SUBA")
        {
            _strBrandClass = "subaru";
        }
        else if (Brand == "SUZU")
        {
            _strBrandClass = "suzuki";
        }
        else if (Brand == "TATA")
        {
            _strBrandClass = "tata";
        }
        else if (Brand == "TOYO")
        {
            _strBrandClass = "toyota";
        }
        else if (Brand == "VOLK")
        {
            _strBrandClass = "volkswagen";
        }
        else if (Brand == "VOLV")
        {
            _strBrandClass = "volvo";
        }
        return _strBrandClass;
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    public void SendAsyncEmail(object sender, EventArgs e)
    {
        //Thread email = new Thread(delegate()
        //{
        //    CE.Email.Welcome.SendMail("kandasvel@gmail.com", "GG Tester", "testing");
        //});

        //email.IsBackground = true;
        //email.Start();
        //ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
    }

    public string GetCarModelName()
    {
        string[] _tempDesc = hidModelBodyCCDoor.Value.Split(' ');
        string _model = "";
        if (_tempDesc.Length == 4)
        {
            _model = _tempDesc[0];
        }
        else if (_tempDesc.Length == 5)
        {
            _model = _tempDesc[0];
        }
        else if (_tempDesc.Length == 6)
        {
            _model = _tempDesc[0] + " " + _tempDesc[1];
        }
        else if (_tempDesc.Length == 7)
        {
            _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
        }
        return _model.Replace('_', ' ');
    }

    protected void lkFacebookLogin_Click(object sender, EventArgs e)
    {
        if (hiddenFacebookID.Value != "")
        {
            txtUserName.Text = hiddenFacebookName.Value;
            txtUserEmail.Text = hiddenFacebookEmail.Value;
            //ViewResultWithFBLogin();
            LinkButton1.Visible = false;
        }
    }

    protected void ViewResultWithFBLogin()
    {
        try
        {
            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();
            _useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            if (_useraccount != null && _useraccount.CEID > 0)
            {
                Session[CE.Global.General.UserId] = _useraccount.CEID.ToString();
                Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId.ToString();
                Session[CE.Global.General.UserEmail] = _useraccount.Email.ToString();
            }
            else
            {
                General.ClearAllSession(this.Page, "USER");
            }

            if (Save())
            {
                Int64 _userId = 0;
                Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
                bool _newuser = false;
                if (Session[General.UserId] != null)
                {
                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                }
                else
                {
                    _newuser = true;
                }

                #region Page Source
                //Sakthi Added on 12 Jun 2014 - Start
                int _intSourceId = 0;
                if (hdnURLFrom.Value != null && hdnURLFrom.Value != string.Empty && hdnURLFrom.Value == "hm")
                {
                    _intSourceId = 1;
                }
                else if (hdnURLFrom.Value != null && hdnURLFrom.Value != string.Empty && hdnURLFrom.Value == "bci")
                {
                    _intSourceId = 2;
                }
                if (_intSourceId > 0 && _carId > 0)
                {
                    UpdateCarQuotePageSourceId(_intSourceId, _carId);
                }
                //Sakthi Added on 12 Jun 2014 - End
                #endregion

                if (UpdateProfile(_userId, _carId) > 0)
                {
                    //Meng Pan Added on 30 Jan 2015 - Start - Insert Facebook ID
                    if (hiddenFacebookEmail.Value != "" && (txtUserEmail.Text.Trim().ToLower() == hiddenFacebookEmail.Value.Trim().ToLower()))
                    {
                        txtUserEmail.Text = hiddenFacebookEmail.Value;
                    }
                    string _strEmail = txtUserEmail.Text.Trim();
                    DataTable _dt = new DataTable();
                    MyDatabase _db = new MyDatabase();
                    string _sqlString = @"SELECT CEID,FacebookID FROM tblCEUser 
                                        WHERE TempEinfo1 = '" + _strEmail + "' And UsrTypeId = 400 And [Status] = 1 ";
                    string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive");
                    if (_strCXLive == "1")
                    {
                        _sqlString = @"OPEN SYMMETRIC KEY CXUserSym DECRYPTION BY CERTIFICATE CXUserCert SELECT CEID,FacebookID FROM tblCEUser 
                                        WHERE CONVERT(VARCHAR(50), DECRYPTBYKEY(EInfo1)) = '" + _strEmail + "' And UsrTypeId = 400 And [Status] = 1 CLOSE SYMMETRIC KEY CXUserSym";
                    }
                    _dt = _db.GetDataTable(_sqlString);
                    _db = null;

                    if (_dt != null && _dt.Rows.Count > 0)
                    {
                        if (_dt.Rows[0]["FacebookID"].ToString() == "")
                        {
                            try
                            {
                                Int64 _result = -1;
                                _db = new MyDatabase();
                                DataTable _dtResult = new DataTable();
                                string _spName = "sprocUserUpdateSingleItemFacebookID";
                                SortedList _sPara = new SortedList();
                                _sPara.Add("@CEID", Int64.Parse(_dt.Rows[0]["CEID"].ToString()));
                                _sPara.Add("@FacebookID", hiddenFacebookID.Value);

                                _result = _db.ExecuteNonSqlSP(_spName, _sPara);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    //Meng Pan Added on 30 Jan 2015 - End - Insert Facebook ID

                    SetCookies();
                    if (_newuser)
                    {
                        SendMailToUser(txtUserEmail.Text.Trim().ToLower(), Session[CE.Global.General.UserName].ToString(), txtUserMobile.Text.Trim()); //txtEmailAddress.Text.Trim()
                    }
                    Session["CLASSTYPE"] = "1";
                    Session["FROMCARDETAIL"] = "1";
                    Response.Redirect(CE.Global.General.GetUrl("/car-insurance/car-quote-results", Page));

                }
                else
                {
                    mpeUserLogin.Show();
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    #region Not Using - Remove on 21 Oct 2014

    //protected void txtUserEmail_TextChanged(object sender, EventArgs e)
    //{
    //    if (EmailValidate("userlogin"))
    //    {
    //        #region Check Customer
    //        Account _useraccount = new Account();
    //        AccountDB _useraccountdb = new AccountDB();

    //        Profile _userprofile = new Profile();
    //        ProfileDB _userprofiledb = new ProfileDB();

    //        Contact _contact = new Contact();
    //        ContactDB _contactdb = new ContactDB();

    //        if (_useraccountdb.IsAlreadyExist(txtUserEmail.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
    //        {
    //            _useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), 400);

    //            if (_useraccount != null && _useraccount.CEID > 0)
    //            {
    //                hdnUserId.Value = _useraccount.CEID.ToString();
    //                _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
    //                if (_userprofile != null && _userprofile.ProfileId > 0)
    //                {
    //                    if (_userprofile.FirstName != string.Empty)
    //                    {
    //                        lblCheckUser.Text = _userprofile.FirstName + " " + _userprofile.SurName;
    //                        txtUserName.Text = _userprofile.FirstName + " " + _userprofile.SurName;
    //                    }
    //                    else
    //                    {
    //                        lblCheckUser.Text = _userprofile.SurName;
    //                        txtUserName.Text = _userprofile.SurName;
    //                    }
    //                }
    //                _contact = _contactdb.GetContact(_useraccount.CEID);
    //                if (_contact != null && _contact.Mobile.Length > 0)
    //                {
    //                    txtUserMobile.Text = _userprofile.SurName;

    //                }
    //                pnlUserQuestion.Visible = true;
    //                pnlUserMobileandName.Visible = false;
    //            }
    //        }
    //        else
    //        {
    //            pnlUserQuestion.Visible = false;
    //            pnlUserMobileandName.Visible = true;
    //        }
    //        #endregion
    //    }
    //}

    //public bool EmailValidate(string strValidationGroup)
    //{
    //    bool _isvalid = false;
    //    if (rfvUserEmail.Enabled && rfvUserEmail.ValidationGroup == strValidationGroup)
    //    {
    //        rfvUserEmail.Validate();
    //        if (rfvUserEmail.IsValid == false)
    //        {
    //            txtUserEmail.ControlStyle.CssClass = "cb-fields-1 validationError";
    //        }
    //        else
    //        {
    //            txtUserEmail.ControlStyle.CssClass = "cb-fields-1";
    //        }
    //    }
    //    else
    //    {
    //        txtUserEmail.ControlStyle.CssClass = "cb-fields-1";
    //    }

    //    if (revUserEmail.Enabled && revUserEmail.ValidationGroup == strValidationGroup)
    //    {
    //        if (rfvUserEmail.IsValid)
    //        {
    //            revUserEmail.Validate();
    //            if (revUserEmail.IsValid == false)
    //            {
    //                txtUserEmail.ControlStyle.CssClass = "cb-fields-1 validationError";
    //            }
    //            else
    //            {
    //                txtUserEmail.ControlStyle.CssClass = "cb-fields-1";
    //            }
    //        }
    //    }
    //    else
    //    {
    //        txtUserEmail.ControlStyle.CssClass = "cb-fields-1";
    //    }
    //    if (!rfvUserEmail.Enabled)
    //    {
    //        _isvalid = true;
    //    }
    //    else if (rfvUserEmail.IsValid)
    //    {
    //        if (!revUserEmail.Enabled)
    //        {
    //            _isvalid = true;
    //        }
    //        else if (revUserEmail.IsValid)
    //        {
    //            _isvalid = true;
    //        }
    //    }
    //    return _isvalid;
    //}

    //protected void btnYes_Click(object sender, EventArgs e)
    //{
    //    try
    //    {
    //        SetCookies();
    //        ChangeValidationEffectServerSide("userlogin");
    //        Page.Validate("userlogin");
    //        if (Page.IsValid)
    //        {
    //            if (Save())
    //            {
    //                Int64 _userId = 0;
    //                Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
    //                bool _newuser = false;
    //                if (Session[General.UserId] != null)
    //                {
    //                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
    //                }
    //                else
    //                {
    //                    _newuser = true;
    //                }

    //                if (UpdateProfile(_userId, _carId) > 0)
    //                {
    //                    if (_newuser)
    //                    {
    //                        //SendMailToUser(EmailAddress, Session[CE.Global.General.UserName].ToString(), txtMobileNo.GetPhoneNo()); //txtEmailAddress.Text.Trim()
    //                    }
    //                    Session["CLASSTYPE"] = "1";
    //                    Session["FROMCARDETAIL"] = "1";
    //                    string url = CE.Global.General.GetUrl("/car-insurance/car-quote-results", Page);
    //                    Response.Redirect(url, false);

    //                }
    //                else
    //                {
    //                    mpeUserLogin.Show();
    //                }
    //            }
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //    }
    //}

    //protected void btnNo_Click(object sender, EventArgs e)
    //{
    //    try
    //    {
    //        hdnUserId.Value = "0";
    //        pnlUserMobileandName.Visible = true;
    //        pnlUserQuestion.Visible = false;
    //        txtUserEmail.Text = "";
    //        txtUserMobile.Text = "";
    //        txtUserName.Text = "";
    //        txtUserEmail.Focus();
    //        mpeUserLogin.Show();
    //    }
    //    catch (Exception ex)
    //    {
    //    }
    //}

    #endregion

}
